iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 22
0

題目:
Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes. Only nodes itself may be changed.

https://ithelp.ithome.com.tw/upload/images/20201007/20111516lAmS2NAE4s.png

思路:
覺得題目沒有描述的很完整,例子也沒有... swap every two adjacent ??? <--怎麽定義的,會不會重複?
只能推測+程式驗證: 從左到右 每兩個為1組 組內對調 , 題目說不是改node的值,但其實直接改node值也OK。
對調的方式 很像 泡泡排序的片段程式碼:
把即將被賦值的先存起來,因為之後會用到。
比如說 先將一組中 較前方的存起來(tmp),將後方的值取代前方的值,最後後方的值由一開始存起來的值取代。

正解:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummyNode = ListNode()
        dummyNode = head
        
        '''
        print(dummyNode)
        print(head.val)
        tmp = head.val
        head.val = head.next.val
        head.next.val = tmp
        
        print(head.val)
        print(head.next.val)
        
        if head.next.next!=None:
            head = head.next.next
            
        tmp = head.val
        head.val = head.next.val
        head.next.val = tmp            
        
        print(head.val)
        print(head.next.val)
        
        
        print(head)
        print(dummyNode)
        return dummyNode
        '''
        
        while head!=None:
            tmp = head.val
            if head==None or head.next==None:
                break
            head.val = head.next.val
            head.next.val = tmp 
            
            head = head.next.next
        return dummyNode

Result:
https://ithelp.ithome.com.tw/upload/images/20201007/20111516HP32pYGl09.png


上一篇
(Hard) 23. Merge k Sorted Lists
下一篇
(Hard) 25. Reverse Nodes in k-Group
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言